package com.jplus.orm.druid;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.druid.pool.DruidDataSource;
import com.jplus.core.InstanceFactory;
import com.jplus.core.core.ConfigHandle;
import com.jplus.core.db.DataSourceFactory;
import com.jplus.core.plugin.Plugin;
import com.jplus.core.util.UUIDUtil;

/**
 * DruidPlugin
 * 
 * @author yuanqy
 *
 */
public class DruidPlugin extends DataSourceFactory implements Plugin {
	Logger logger = LoggerFactory.getLogger(getClass());
	private DruidDataSource dataSource;
	private String prefix = "db";

	@Override
	public void init() {
		try {
			dataSource = new DruidDataSource();
			dataSource.setDriverClassName(ConfigHandle.getString(prefix + ".driver"));
			dataSource.setUrl(ConfigHandle.getString(prefix + ".url"));
			dataSource.setUsername(ConfigHandle.getString(prefix + ".username"));
			dataSource.setPassword(ConfigHandle.getString(prefix + ".password"));
			// ==public
			dataSource.setInitialSize(ConfigHandle.getInt(prefix + ".initialSize", 3));
			dataSource.setMinIdle(ConfigHandle.getInt(prefix + ".minIdle", 3));
			dataSource.setMaxActive(ConfigHandle.getInt(prefix + ".maxActive", 21));
			dataSource.setMaxWait(ConfigHandle.getInt(prefix + ".maxWait", 60000));
			dataSource.setRemoveAbandoned(true);
			dataSource.setRemoveAbandonedTimeout(1800);
			ConfigHandle.setProp(InstanceFactory.DS_FACTORY, getClass().getName());
		} catch (RuntimeException e) {
			dataSource = null;
			logger.error("DruidPlugin start error");
			throw new RuntimeException(e);
		}
	}

	public DruidPlugin(DruidDataSource dataSource) {
		this.dataSource = dataSource;
	}

	public DruidPlugin(String prefix) {
		this.prefix = prefix;
	}

	public DruidPlugin() {
	}

	public DruidPlugin(String jdbcUrl, String user, String pwd, String driverClass) {
		this.prefix = UUIDUtil.getUUID(6, 62);
		ConfigHandle.setProp(prefix + ".url", jdbcUrl);
		ConfigHandle.setProp(prefix + ".username", user);
		ConfigHandle.setProp(prefix + ".password", pwd);
		ConfigHandle.setProp(prefix + ".driver", driverClass);
		init();
	}

	@Override
	public void destroy() {
		dataSource.close();
	}

	@Override
	public DataSource getDataSource() {
		return dataSource;
	}

}
